package org.klarton.filter.goertzel;

import org.klarton.filter.Filter;

import java.util.ArrayList;
import java.util.List;

/**
 * This filter implementation uses the {@link GoertzelAlgorithm} to process the incoming values.
 */
public class GoertzelFilter extends Filter {

    private final List<Double> buffer = new ArrayList<Double>();
    private final int bufSize;
    private final GoertzelAlgorithm algorithm;

    public GoertzelFilter(String name, double targetFrequency, double sampleRate, double bandwidth) {
        super(name, targetFrequency);
        bufSize = (int)Math.ceil(sampleRate / bandwidth);
        algorithm = new GoertzelAlgorithm(targetFrequency, sampleRate);
    }

    public void read(double... samples) {
        for (double sample : samples) {
            buffer.add(sample);
        }
        // remove the oldest values, unless the buffer is not full.
        while (buffer.size() > bufSize) {
            buffer.remove(0);
        }
        // recalculate with the goertzel algorithm.
        algorithm.reset();
        for (double value : buffer) {
            algorithm.read(value);
        }
        setValue(Math.sqrt(algorithm.getValue() / bufSize));
    }
}
